package com.hnust.service.impl;

import com.hnust.config.YamlReader;
import com.hnust.dao.*;
import com.hnust.domain.*;
import com.hnust.domain.accept.PaperData;
import com.hnust.domain.record.*;
import com.hnust.service.PaperService;
import com.hnust.util.IDUtil;
import com.hnust.util.ReplaceTextWithImage;
import com.hnust.util.Tools;
import com.hnust.util.URIInputStream;
import com.spire.doc.*;
import com.spire.doc.collections.CellCollection;
import com.spire.doc.documents.*;
import com.hnust.dao.PaperDao;
import com.hnust.dao.QuestionDao;
import com.hnust.dao.QuestionPaperDao;
import com.hnust.dao.QuestionTypeDao;
import com.hnust.domain.Paper;
import com.hnust.domain.Question;
import com.hnust.domain.QuestionType;
import com.hnust.domain.record.PageData;
import com.hnust.domain.record.QuestionTypeRecord;
import com.hnust.domain.record.SubjectDataRecord;
import com.hnust.domain.record.SubjectInfo;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 创建人：gh
 * 创建时间：2020/10/29
 * 描述：
 */
@Service("paperService")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 3600, rollbackFor = Exception.class)
public class PaperServiceImpl implements PaperService {

    @Autowired
    private PaperDao paperDao;

    @Autowired
    private QuestionPaperDao questionPaperDao;

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private TeacherDao teacherDao;
    @Autowired
	private CourseDao courseDao;
    @Autowired
	private CollegeDao collegeDao;
    @Autowired
	private AlternativeAnswerDao alternativeAnswerDao;
    @Autowired
	private CourseTargetDao courseTargetDao;
    @Autowired
	private GradRequirementsDao gradRequirementsDao;

    // 我们这里使用set方法注入来进行注入操作
    private QuestionTypeDao questionTypeDao;
    @Autowired
    public PaperServiceImpl(QuestionTypeDao questionTypeDao){
        this.questionTypeDao = questionTypeDao;
    }

    // 试卷管理---删除试卷
    @Override
    public boolean delTestPaper(String paper_id) {
    	int result = 1;
    	try {
			result = paperDao.delTestPaper(paper_id);
			if(result == 0){
				return false;
			}
			//删除试卷文档
			File file = new File(System.getProperty("user.dir") + "/assets/paper/"+paper_id+".docx");
			file.deleteOnExit();
			//删除计划表文档
			file = new File(System.getProperty("user.dir") + "/assets/plan/"+paper_id+".docx");
			file.deleteOnExit();
			//删除预览文档
			file = new File(System.getProperty("user.dir") + "/assets/pdf/"+paper_id+".pdf");
			file.deleteOnExit();
			//删除答案文档
			file = new File(System.getProperty("user.dir") + "/assets/answer/"+paper_id+".docx");
			file.deleteOnExit();
		}catch(Exception e){
    		result = 0;
		}
		return result==1;
    }

    /**
     * 获取试卷列表
     * @param id 教师id
     * @param course_id 课程id
     * @param now_page 当前第几页
     * @return PageData的list
     */
    @Override
    public List<PageData> getPaperList(String id, String course_id, int now_page) {
        return paperDao.getPaperList((now_page - 1) * 8, course_id, id);
    }

    /**
     * 获取试卷的总数
     * @param course_id 课程id
     * @param id 老师id
     * @return 总的数量
     */
    @Override
    public int getPaperListCount(String course_id, String id) {
        return paperDao.getPaperListCount(course_id, id);
    }

    /**
     * 保存试卷
     * @param paperData 试卷和题目信息
     * @return 是否保存成功
     */
    @Override
    // transaction是事务的注解
    public boolean saveCompletePaper(PaperData paperData) {
        // 插入数据库
        Paper paper = new Paper();
        paper.setPapId(IDUtil.getPrimaryKey());
        paper.setPassRate(paperData.getPassRate());
        paper.setName(paperData.getName());
        paper.setProTeacher(paperData.getProTeacher());
        paper.setTime(paperData.getTime());
        paper.setExamTime(paperData.getExamTime());
        paper.setCouNumber(paperData.getCouNumber());
        paper.setGrade(paperData.getGrade());
        paper.setIsSample(paperData.getIsSample());
        paper.setIsAb(paperData.getIsAb());
        paper.setCollegeId(paperData.getCollegeId());
        if (paperDao.addPaper(paper) == 1){
            List<String> questions =  paperData.getQuestions();
            // 插入试题记录
            for (String question : questions) {
                questionPaperDao.insertQuestionRecord(IDUtil.getPrimaryKey(),question, paper.getPapId());
            }
            return true;
        } else {
            return false;
        }
    }
    /**
     * 将试卷设为样卷
     * @param pap_id 试卷id
     * @return 返回影响行数
     */
    @Override
    public boolean setPaperToSample(String pap_id) {
        return paperDao.setPaperToSample(pap_id) == 1;
    }

	/**
	 * 试卷列表 --- 设置试卷不为样卷
	 * @param pap_id 试卷id
	 * @return 返回影响行数
	 */
	@Override
	public boolean removePaperToSample(String pap_id) {
		return paperDao.removePaperToSample(pap_id) == 1;
	}

	/**
     * 获取所有的题型信息
     *
     * @return 返回所有的题型信息
     */
    @Override
    public List<QuestionTypeRecord> getAllQuestionType() {
        List<QuestionType> types = questionTypeDao.getAllQuestionType();
        List<QuestionTypeRecord> records = new  ArrayList<>();
        for(QuestionType type : types){
			int typeId = Integer.parseInt(type.getQueTypId());
            records.add(new QuestionTypeRecord(typeId, type.getName()));
        }
        return records;
    }

	/**
	 * 自动生成试卷
	 * @param listPaperQues 参数对象
	 * @return 结果
	 */
	@Override
	public List<SubjectData> getAutoPaper(List<PaperQues> listPaperQues, String course_id) {
		List<SubjectData> subjectDataList = new ArrayList<>();
		// 存储简单的
		List<SubjectData> tempSimple = new ArrayList<>();
		// 存储中等的
		List<SubjectData> tempSecond = new ArrayList<>();
		// 存储困难的
		List<SubjectData> tempDifficult = new ArrayList<>();
		// 先遍历要出那些类型的题目，以及题目的类型有哪些

		for(int i = 0; i < listPaperQues.size(); i ++){
			// 先获取这个题型所有难度的题目
			// 转换类型
			PaperQues paperQues = ((PaperQues) JSONObject.toBean(JSONObject.fromObject(listPaperQues.get(i)), PaperQues.class));

			tempSimple = questionDao.getCourseQuesListAll(course_id, paperQues.getQues_type_id(), 1);
			tempSecond = questionDao.getCourseQuesListAll(course_id, paperQues.getQues_type_id(), 2);
			tempDifficult = questionDao.getCourseQuesListAll(course_id, paperQues.getQues_type_id(), 3);
			// 然后再随机抽取题目
			List<Integer> listNum = null;
			// 先获取简单类型的
			listNum = Tools.getNumRandom(tempSimple.size(), paperQues.getSimple_num());
			// 先存放简单类型的题目
			for(int j = 0; j < listNum.size(); j ++){
				subjectDataList.add(tempSimple.get(listNum.get(j)));
			}
			// 中等类型的
			listNum = Tools.getNumRandom(tempSecond.size(), paperQues.getSecondary_num());
			// 先存放中等难度类型的题目
			for(int j = 0; j < listNum.size(); j ++){
				subjectDataList.add(tempSecond.get(listNum.get(j)));
			}
			// 困难类型的
			listNum = Tools.getNumRandom(tempDifficult.size(), paperQues.getDifficult_num());
			// 先存放困难难度类型的题目
			for(int j = 0; j < listNum.size(); j ++){
				subjectDataList.add(tempDifficult.get(listNum.get(j)));
			}
		}
		// 然后获取题目的答案
		for (int i = 0; i < subjectDataList.size(); i++) {
			// 获取题目里面的答案列表
			subjectDataList.get(i).setAnswer(questionDao.getCourseQuesAnswerList(subjectDataList.get(i).getId()));
		}
		return subjectDataList;
	}

	/**
     * 获取某个课程，某个题型的所有题目
     * @param cou_id 课程id
     * @param type_id 题目类型
     * @param now_page 当前第几页
     * @return list
     */
    @Override
    public SubjectInfo getCourseQuesList(String cou_id, String type_id, int now_page) {
        SubjectInfo subjectInfo = new SubjectInfo();
        // 先获取总数
        subjectInfo.setTotal(questionDao.getCourseQuesCount(cou_id, type_id));
        // 然后获取题目列表
        List<SubjectData> subjectDataList = new ArrayList<>();
        subjectDataList = questionDao.getCourseQuesList(cou_id, type_id, (now_page - 1) * 5);
        // 然后遍历题目，获取每个题目的答案列表
        for (int i = 0; i < subjectDataList.size(); i++) {
            // 获取题目里面的答案列表
            subjectDataList.get(i).setAnswer(questionDao.getCourseQuesAnswerList(subjectDataList.get(i).getId()));
        }
        subjectInfo.setSubject(subjectDataList);
        return subjectInfo;
    }


    /*
     * @Author Tonited
     * @Description //TODO 生成文件和图片，并将试卷记录存入数据库
     * @Date 10:40 2020/10/31
     * @Param [info]
     * @return java.lang.String
     **/
    @Override
    public String getPaperPreview(GeneratePapaerInfoRecord info) throws Exception {
        String fileName = IDUtil.getPrimaryKey();
        String filePath = System.getProperty("user.dir") + "/assets/paper/"+fileName+".docx";
        try {
			createPaperDocxAndPic(filePath,fileName,info);
			createAnswer(filePath,fileName,info);
		}catch (Exception e){
			throw e;
		}
        return fileName;
    }

	/*
	 * @Author Tonited
	 * @Description //TODO 生成doc文件和预览图、以及出题计划表的工具方法，并将试卷记录存入数据库
	 * @Date 16:41 2020/10/31
	 * @Param [path, info]
	 * @return void
	 **/
    @Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public void createPaperDocxAndPic(String path, String id, GeneratePapaerInfoRecord info) throws Exception {
    	try {
    		if(info.getQuestions().size()==0){
    			throw new Exception("无题目");
			}
			//获取所需数据
			//获取命题教师姓名
			String teacherName = teacherDao.getTeacherNameById(info.getTeacherId());
			if(teacherName==null){
				throw new Exception("教师ID异常");
			}
			//获取学院名
			String collegeName = collegeDao.getCollegeNameById(info.getCollegeId());
			if(collegeName==null){
				throw new Exception("学院ID异常");
			}
			//获取课程名称
			String courseName = courseDao.getCourse(info.getCourseId());
			if(courseName==null){
				throw new Exception("课程ID异常");
			}
			String courseNum = courseDao.getCourseNumById(info.getCourseId());
			if(courseNum==null){
				throw new Exception("课程代码异常");
			}
			//获取考试时长
			String examTime = info.getExamTime().replace("分","").replace("钟","");
			//获取年级
			String grade = info.getGrade();
			//获取AB卷
			String type =info.getType();
			//获取题目列表
			List<PaperQuestionRecord> questions = info.getQuestions();

			//创建Word文档
			Document document = new Document();
			//添加一个section
			Section section = document.addSection();
			//设置页边距
			section.getPageSetup().getMargins().setTop(60f);
			section.getPageSetup().getMargins().setBottom(60f);
			section.getPageSetup().getMargins().setLeft(60f);
			section.getPageSetup().getMargins().setRight(60f);


			//创建段落样式以给段落设置字体名称和字号：大标题
			ParagraphStyle paperTitleStyle = new ParagraphStyle(document);
			paperTitleStyle.setName("paperTitle");
			paperTitleStyle.getCharacterFormat().setFontName("宋体");
			paperTitleStyle.getCharacterFormat().setFontSize(22f);
			paperTitleStyle.getCharacterFormat().setBold(true);
			paperTitleStyle.getParagraphFormat().setBeforeAutoSpacing(false);
			paperTitleStyle.getParagraphFormat().setBeforeSpacing(11);
			paperTitleStyle.getParagraphFormat().setAfterAutoSpacing(false);
			paperTitleStyle.getParagraphFormat().setAfterSpacing(11);
			paperTitleStyle.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
			document.getStyles().add(paperTitleStyle);

			//大标题
			Paragraph titleParagraph = section.addParagraph();
			titleParagraph.appendText("湖南科技大学考试试题纸("+type+"卷)");
			titleParagraph.applyStyle(paperTitleStyle.getName());

			//创建段落样式以给段落设置字体名称和字号：Header
			ParagraphStyle headerStyle = new ParagraphStyle(document);
			headerStyle.setName("header");
			headerStyle.getCharacterFormat().setFontName("宋体");
			headerStyle.getCharacterFormat().setFontSize(14f);
			headerStyle.getCharacterFormat().setBold(true);
			paperTitleStyle.getParagraphFormat().setBeforeAutoSpacing(false);
			paperTitleStyle.getParagraphFormat().setBeforeSpacing(7);
			paperTitleStyle.getParagraphFormat().setAfterAutoSpacing(false);
			paperTitleStyle.getParagraphFormat().setAfterSpacing(7);
			paperTitleStyle.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
			document.getStyles().add(headerStyle);

			//Header
			Paragraph headerParagraph = section.addParagraph();
			headerParagraph.appendText("课程名称: "+courseName+"    开课单位: "+collegeName+"\n"
				+"命题教师: "+teacherName+"    授课对象: ____________学院 "+grade+"年级\n"
				+"考试时量: "+examTime+"分钟    考核方式: ______    考试方式: ______\n"
				+"审核人: ____________         审核时间: ______年___月___日 ");
			headerParagraph.applyStyle(headerStyle.getName());


			ParagraphStyle queStyle = new ParagraphStyle(document);
			queStyle.setName("queStyle");
			queStyle.getCharacterFormat().setFontName("宋体");
			queStyle.getCharacterFormat().setFontSize(12f);
			queStyle.getCharacterFormat().setBold(false);
			queStyle.getParagraphFormat().setBeforeAutoSpacing(false);
			queStyle.getParagraphFormat().setBeforeSpacing(2);
			queStyle.getParagraphFormat().setAfterAutoSpacing(false);
			queStyle.getParagraphFormat().setAfterSpacing(2);
			queStyle.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
			document.getStyles().add(queStyle);

			//题目区
			Table table = section.addTable(true);
			table.resetCells(1,1);
			table.getTableFormat().getBorders().setBorderType(BorderStyle.Hairline);
			table.getTableFormat().getBorders().setLineWidth(1.3F);
			TableRow row = table.getRows().get(0);
			TableCell cell = row.getCells().get(0);

			//选择
			List<PaperQuestionDetailRecord> chooseQue = new ArrayList<>();
			//填空
			List<PaperQuestionDetailRecord> blankQue = new ArrayList<>();
			//简答
			List<PaperQuestionDetailRecord> ansQue = new ArrayList<>();
			//题目类型分拣处理
			for(PaperQuestionRecord questionRecord : questions){
				PaperQuestionDetailRecord paperQuestionDetailRecord = new PaperQuestionDetailRecord();
				Question question  = questionDao.queryQuestionById(questionRecord.getQuestionID());
				if(question==null){
					throw new Exception("题目ID错误");
				}
				List<AlternativeAnswer> alternativeAnswers = alternativeAnswerDao.queryAlternativeAnswersByQuestionId(questionRecord.getQuestionID());
				paperQuestionDetailRecord.setAlternativeAnswers(alternativeAnswers);
				paperQuestionDetailRecord.setContent(question.getContent());
				paperQuestionDetailRecord.setScore(questionRecord.getScore());
				paperQuestionDetailRecord.setLevel(question.getLevel());
				paperQuestionDetailRecord.setPoint(question.getPoint());
				paperQuestionDetailRecord.setTagetId(question.getCouTarId());
				paperQuestionDetailRecord.setTypeId(question.getQueTypId());
				String typeName = questionTypeDao.getQeuTypeNameByQueTypId(question.getQueTypId());
				if(typeName==null){
					throw new Exception("题目类型id错误");
				}
				if(typeName.contains("选")){
					chooseQue.add(paperQuestionDetailRecord);
				}else if(typeName.contains("填")){
					blankQue.add(paperQuestionDetailRecord);
				}else{
					ansQue.add(paperQuestionDetailRecord);
				}
			}


			//选择题区域
			int count =1;//题目计数器
			int queTitileCount = 0;//大题目计数器
			//选择题总标题
			Paragraph chooseTitle = null;
			if(chooseQue.size()>0) {
				chooseTitle = cell.addParagraph();
				chooseTitle.appendText("选择题");
				queTitileCount++;
				chooseTitle.applyStyle(headerStyle.getName());
				//题目区
				Paragraph chooseQueAre = cell.addParagraph();
				chooseQueAre.applyStyle(queStyle.getName());
				for(PaperQuestionDetailRecord question : chooseQue){
					//题目内容
					question.setQueNum(queTitileCount+"-"+ count);
					chooseQueAre.appendText(count+++"、"+"("+question.getScore()+"分)"+question.getContent().replace("&nbsp"," ").replace("<p>","").replace("</p>","\n    ")+"\n");
					int itemTag = 65;
					for(AlternativeAnswer answer : question.getAlternativeAnswers()){
						chooseQueAre.appendText("\t"+(char)(itemTag++)+"、 "+answer.getContent().replace("&nbsp"," ").replace("<p>","").replace("</p>","\n"));
					}
				}
			}

			//填空题区域
			count =1;//题目计数器
			//填空题总标题
			Paragraph blankTitle = null;
			if(blankQue.size()>0) {
				blankTitle = cell.addParagraph();
				blankTitle.appendText("填空题");
				queTitileCount++;
				blankTitle.applyStyle(headerStyle.getName());
				//题目区
				Paragraph blankQueAre = cell.addParagraph();
				blankQueAre.applyStyle(queStyle.getName());
				for (PaperQuestionDetailRecord question : blankQue) {
					//题目内容
					question.setQueNum(queTitileCount + "-" + count);
					blankQueAre.appendText(count++ + "、" + "(" + question.getScore() + "分)" + question.getContent().replace("&nbsp", " ").replace("<p>", "").replace("</p>", "\n    ") + "\n");
				}
			}

			//简答题区域
			count =1;//题目计数器
			//简答题总标题
			Paragraph ansTitle = null;
			if(ansQue.size()>0) {
				ansTitle = cell.addParagraph();
				ansTitle.appendText("简答题");
				queTitileCount++;
				ansTitle.applyStyle(headerStyle.getName());
				//题目区
				Paragraph ansQueAre = cell.addParagraph();
				ansQueAre.applyStyle(queStyle.getName());
				for (PaperQuestionDetailRecord question : ansQue) {
					question.setQueNum(queTitileCount + "-" + count);
					//题目内容
					ansQueAre.appendText(count++ + "、" + "(" + question.getScore() + "分)" + question.getContent().replace("&nbsp", " ").replace("<p>", "").replace("</p>", "\n    ") + "\n");
				}
			}


			//整合所有题目
			List<PaperQuestionDetailRecord> allPaperQuestionDetailRecord = new ArrayList<>();
			allPaperQuestionDetailRecord.addAll(chooseQue);
			allPaperQuestionDetailRecord.addAll(blankQue);
			allPaperQuestionDetailRecord.addAll(ansQue);
			createTable(path,id,allPaperQuestionDetailRecord);


			//题目中插入图片
			ReplaceTextWithImage.WriteImage(document);

			//保存文件
			document.saveToFile(path, FileFormat.Docx);

			//将图片数据保存为PDF格式文档
			document.saveToFile((path+"").replace("paper","pdf").replace("docx","pdf"), FileFormat.PDF);

			//试卷存入数据库
			int isab = type.contains("A")?1:0;
			SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MM/dd");
			String dateString = formatter.format(new Date(System.currentTimeMillis()));
			paperDao.addPaper(new Paper(id,"",courseName+" "+type+"卷",info.getTeacherId(),dateString, info.getExamTime(),courseNum,info.getGrade(),0,isab,info.getCollegeId()));
    	}catch (Exception e){
			File willDeleteFile = new File(path);
			willDeleteFile.delete();
			willDeleteFile = new File((path+"").replace("paper","plan"));
			willDeleteFile.delete();
			willDeleteFile= new File((path+"").replace("paper","pdf").replace("docx","pdf"));
			willDeleteFile.delete();
			throw e;
		}
    }

	public void createAnswer(String path, String id, GeneratePapaerInfoRecord info) throws Exception {
		try {
			//获取题目列表
			List<PaperQuestionRecord> questions = info.getQuestions();

			//创建Word文档
			Document document = new Document();
			//添加一个section
			Section section = document.addSection();
			//设置页边距
			section.getPageSetup().getMargins().setTop(60f);
			section.getPageSetup().getMargins().setBottom(60f);
			section.getPageSetup().getMargins().setLeft(60f);
			section.getPageSetup().getMargins().setRight(60f);

			//创建段落样式以给段落设置字体名称和字号：Header
			ParagraphStyle headerStyle = new ParagraphStyle(document);
			headerStyle.setName("header");
			headerStyle.getCharacterFormat().setFontName("宋体");
			headerStyle.getCharacterFormat().setFontSize(14f);
			headerStyle.getCharacterFormat().setBold(true);
			document.getStyles().add(headerStyle);

			ParagraphStyle queStyle = new ParagraphStyle(document);
			queStyle.setName("queStyle");
			queStyle.getCharacterFormat().setFontName("宋体");
			queStyle.getCharacterFormat().setFontSize(12f);
			queStyle.getCharacterFormat().setBold(false);
			queStyle.getParagraphFormat().setBeforeAutoSpacing(false);
			queStyle.getParagraphFormat().setBeforeSpacing(2);
			queStyle.getParagraphFormat().setAfterAutoSpacing(false);
			queStyle.getParagraphFormat().setAfterSpacing(2);
			queStyle.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
			document.getStyles().add(queStyle);

			//题目区
			Table table = section.addTable(true);
			table.resetCells(1,1);
			table.getTableFormat().getBorders().setBorderType(BorderStyle.Hairline);
			table.getTableFormat().getBorders().setLineWidth(1.3F);
			TableRow row = table.getRows().get(0);
			TableCell cell = row.getCells().get(0);

			//选择
			List<PaperQuestionDetailRecord> chooseQue = new ArrayList<>();
			//填空
			List<PaperQuestionDetailRecord> blankQue = new ArrayList<>();
			//简答
			List<PaperQuestionDetailRecord> ansQue = new ArrayList<>();
			//题目类型分拣处理
			for(PaperQuestionRecord questionRecord : questions){
				PaperQuestionDetailRecord paperQuestionDetailRecord = new PaperQuestionDetailRecord();
				Question question  = questionDao.queryQuestionById(questionRecord.getQuestionID());
				if(question==null){
					throw new Exception("题目ID错误");
				}
				List<AlternativeAnswer> alternativeAnswers = alternativeAnswerDao.queryAlternativeAnswersByQuestionId(questionRecord.getQuestionID());
				paperQuestionDetailRecord.setAlternativeAnswers(alternativeAnswers);
				paperQuestionDetailRecord.setTypeId(question.getQueTypId());
				paperQuestionDetailRecord.setScore(questionRecord.getScore());
				String typeName = questionTypeDao.getQeuTypeNameByQueTypId(question.getQueTypId());
				if(typeName==null){
					throw new Exception("题目类型id错误");
				}
				if(typeName.contains("选")){
					chooseQue.add(paperQuestionDetailRecord);
				}else if(typeName.contains("填")){
					blankQue.add(paperQuestionDetailRecord);
				}else{
					ansQue.add(paperQuestionDetailRecord);
				}
			}


			//选择题区域
			int count =1;//题目计数器
			int queTitileCount = 0;//大题目计数器
			//选择题总标题
			Paragraph chooseTitle = null;
			if(chooseQue.size()>0) {
				chooseTitle = cell.addParagraph();
				chooseTitle.appendText("选择题");
				queTitileCount++;
				chooseTitle.applyStyle(headerStyle.getName());
				//题目区
				Paragraph chooseQueAre = cell.addParagraph();
				chooseQueAre.applyStyle(queStyle.getName());
				for(PaperQuestionDetailRecord question : chooseQue){
					//题目内容
					question.setQueNum(queTitileCount+"-"+ count);
					chooseQueAre.appendText(count+++"、"+"("+question.getScore()+"分)" + "\n");
					int itemTag = 65;
					for(AlternativeAnswer answer : question.getAlternativeAnswers()) {
						if (answer.getRight() == 1) {
							chooseQueAre.appendText("\t" + answer.getContent().replace("&nbsp", " ").replace("<p>", "").replace("</p>", "\n"));
						}
					}
				}
			}

			//填空题区域
			count =1;//题目计数器
			//填空题总标题
			Paragraph blankTitle = null;
			if(blankQue.size()>0) {
				blankTitle = cell.addParagraph();
				blankTitle.appendText("\n填空题");
				queTitileCount++;
				blankTitle.applyStyle(headerStyle.getName());
				//题目区
				Paragraph blankQueAre = cell.addParagraph();
				blankQueAre.applyStyle(queStyle.getName());
				for (PaperQuestionDetailRecord question : blankQue) {
					//题目内容
					question.setQueNum(queTitileCount + "-" + count);
					blankQueAre.appendText(count++ + "、" + "(" + question.getScore() + "分)" + "\n");
					for(AlternativeAnswer answer : question.getAlternativeAnswers()) {
						if (answer.getRight() == 1) {
							blankQueAre.appendText("\t" + answer.getContent().replace("&nbsp", " ").replace("<p>", "").replace("</p>", "\n"));
						}
					}
				}
			}

			//简答题区域
			count =1;//题目计数器
			//简答题总标题
			Paragraph ansTitle = null;
			if(ansQue.size()>0) {
				ansTitle = cell.addParagraph();
				ansTitle.appendText("\n简答题");
				queTitileCount++;
				ansTitle.applyStyle(headerStyle.getName());
				//题目区
				Paragraph ansQueAre = cell.addParagraph();
				ansQueAre.applyStyle(queStyle.getName());
				for (PaperQuestionDetailRecord question : ansQue) {
					question.setQueNum(queTitileCount + "-" + count);
					//题目内容
					ansQueAre.appendText(count++ + "、" + "(" + question.getScore() + "分)" + "\n");
					for(AlternativeAnswer answer : question.getAlternativeAnswers()) {
						if (answer.getRight() == 1) {
							ansQueAre.appendText("\t" + answer.getContent().replace("&nbsp", " ").replace("<p>", "").replace("</p>", "\n"));
						}
					}
				}
			}



			//题目中插入图片
			ReplaceTextWithImage.WriteImage(document);

			//保存文件
			document.saveToFile(path.replace("paper","answer"), FileFormat.Docx);

		}catch (Exception e){
			File willDeleteFile = new File(path);
			willDeleteFile.delete();
			throw e;
		}
	}

	/*
     * @Author Tonited
     * @Description //TODO private 创建试卷出题计划表的工具方法
     * @Date 20:19 2020/11/1
     * @Param [path, id, allPaperQuestionDetailRecord]
     * @return void
     **/
    private void createTable(String path, String id, List<PaperQuestionDetailRecord> allPaperQuestionDetailRecord) throws Exception {
    	path = path.replace("paper","plan");
		//创建Word文档
		Document document = new Document();
		//添加一个section
		Section section = document.addSection();

		//创建表头样式
		ParagraphStyle headerStyle = new ParagraphStyle(document);
		headerStyle.setName("headerStyle");
		headerStyle.getCharacterFormat().setFontName("宋体");
		headerStyle.getCharacterFormat().setFontSize(10.5f);
		headerStyle.getCharacterFormat().setBold(true);
		headerStyle.getParagraphFormat().setBeforeAutoSpacing(false);
		headerStyle.getParagraphFormat().setBeforeSpacing(2);
		headerStyle.getParagraphFormat().setAfterAutoSpacing(false);
		headerStyle.getParagraphFormat().setAfterSpacing(2);
		headerStyle.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
		document.getStyles().add(headerStyle);

		//创建段落样式
		ParagraphStyle style = new ParagraphStyle(document);
		style.setName("style");
		style.getCharacterFormat().setFontName("宋体");
		style.getCharacterFormat().setFontSize(10.5f);
		style.getCharacterFormat().setBold(false);
		style.getParagraphFormat().setBeforeAutoSpacing(false);
		style.getParagraphFormat().setBeforeSpacing(2);
		style.getParagraphFormat().setAfterAutoSpacing(false);
		style.getParagraphFormat().setAfterSpacing(2);
		style.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
		document.getStyles().add(style);

		//表头
		String[] header = {"课程目标","支撑毕业要求指标点","总分值","题型","考核覆盖教学内容","对应题号","分值","难易度"};
		//添加表格
		Table table = section.addTable(true);
		//设置表格的行数和列数
		table.resetCells(1, header.length);

		//设置第一行作为表格的表头
		TableRow row = table.getRows().get(0);
		row.isHeader(true);
		row.setHeight(50);
		row.setHeightType(TableRowHeightType.Exactly);
		//设置表头
		for (int i = 0; i < header.length; i++) {
			row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
			Paragraph p = row.getCells().get(i).addParagraph();
			p.appendText(header[i]);
			p.applyStyle(headerStyle.getName());
		}

		//获得所有课程目标及其对应的题目
		Map<String,List<PaperQuestionDetailRecord>> couMapRec = new TreeMap<>();
		for(PaperQuestionDetailRecord paperQuestionDetailRecord : allPaperQuestionDetailRecord){
			String courseTargetId = paperQuestionDetailRecord.getTagetId();
			if(!couMapRec.containsKey(courseTargetId)){
				couMapRec.put(courseTargetId,new ArrayList<>());
			}
			couMapRec.get(courseTargetId).add(paperQuestionDetailRecord);
		}
		int rowCount = 0;//计算该题目一共有多少行(0起)
		int nowRowCount = 1;
		for(String couTarId : couMapRec.keySet()){
			//获取课程目标
			CourseTarget couTar = courseTargetDao.getCourseTargetById(couTarId);
			if(couTar==null){
				throw new Exception("课程目标id错误");
			}
			//获取课程目标对应的毕业指标点
			GradRequirements gradRequirements = gradRequirementsDao.getGradReqById(couTar.getGradId());
			if(gradRequirements==null){
				throw new Exception("获取课程目标对应毕业指标点时发生错误");
			}
			int totalScore = 0;//总分值
			boolean isFirstLine = true;
			//添加题目信息
			for(PaperQuestionDetailRecord question : couMapRec.get(couTarId)){
				rowCount++;//增加当前题目中的行计数

				TableRow queRow = table.addRow();
				CellCollection queCells = queRow.getCells();
				if(isFirstLine){
					//添加课程学习目标
					Paragraph couTarPar = queCells.get(0).addParagraph();
					couTarPar.appendText("课程学习目标:"+couTar.getNum()+"、"+couTar.getContent());
					couTarPar.applyStyle(style.getName());

					//添加毕业要求指标点
					Paragraph gradTarPar = queCells.get(1).addParagraph();
					gradTarPar.appendText(gradRequirements.getNum()+"、"+gradRequirements.getContent());
					gradTarPar.applyStyle(style.getName());
					isFirstLine = false;
				}
				//添加题型
				Paragraph queTypePar = queCells.get(3).addParagraph();
				String typeName = questionTypeDao.getQeuTypeNameByQueTypId(question.getTypeId());
				queTypePar.appendText(typeName);
				queTypePar.applyStyle(style.getName());

				//添加考点覆盖内容(知识点)
				Paragraph pointPar = queCells.get(4).addParagraph();
				String point = question.getPoint();
				pointPar.appendText(point);
				pointPar.applyStyle(style.getName());

				//添加对应题号
				Paragraph numPar = queCells.get(5).addParagraph();
				String num = question.getQueNum();
				numPar.appendText(num);
				numPar.applyStyle(style.getName());

				//添加分值
				Paragraph scorePar = queCells.get(6).addParagraph();
				Integer score = question.getScore();
				scorePar.appendText(String.valueOf(score));
				scorePar.applyStyle(style.getName());
				totalScore+=score;//增加总分值

				//添加难易度
				Paragraph levelPar = queCells.get(7).addParagraph();
				int  levelInt = question.getLevel();
				String level = null;
				switch (levelInt){
					case 1: level = "简单"; break;
					case 2: level = "中等"; break;
					case 3: level = "困难"; break;
					default: break;
				}
				levelPar.appendText(level);
				levelPar.applyStyle(style.getName());
			}

			//合并课程目标列
			table.applyVerticalMerge(0, nowRowCount, rowCount);
			//合并毕业指标列
			table.applyVerticalMerge(1, nowRowCount, rowCount);
			//添加总分值
			Paragraph totalScorePar = table.getRows().get(nowRowCount).getCells().get(2).addParagraph();
			totalScorePar.appendText(String.valueOf(totalScore));
			totalScorePar.applyStyle(style.getName());
			//合并总分值列
			table.applyVerticalMerge(2, nowRowCount, rowCount);
			nowRowCount = rowCount+1;
		}
		table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);
		table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);
		document.saveToFile(path, FileFormat.Docx);
	}

	/**
	 * 根据课程id，题目类型，关键词，当前页数来查找题目
	 *
	 * @param courseId 课程id
	 * @param typeId   题目类型
	 * @param keyword  关键词
	 * @param now      当前页数
	 * @return 返回值类型
	 */
	@Override
	public SubjectInfo searchQuestionByCon(String courseId, String typeId, String keyword, Integer now,Integer diff) {
//		if ("".equals(keyword)) {
//			keyword = "7878787878787878";
//		}
		float row = 5;
		List<Question> questions =  questionDao.searchQuestionByCon(courseId,typeId,keyword,(now-1)*5, (int) row,diff);
		SubjectInfo info = new SubjectInfo();
		List<SubjectData> subjectData = new ArrayList<>();
		// 遍历所有题目
		for (Question question : questions){
			SubjectData subjectData1 = new SubjectData();
			subjectData1.setId(question.getQueId());
			subjectData1.setContent(question.getContent());
			subjectData1.setCourseId(question.getCouId());
			subjectData1.setChapterId(question.getChaId());
			subjectData1.setType(question.getQueTypId());
			subjectData1.setDifficult(question.getLevel());
			subjectData1.setResolve(question.getAnalysis());
			subjectData1.setKnowledgePointer(question.getPoint());
			subjectData1.setAnswer(questionDao.getCourseQuesAnswerList(question.getQueId()));
			subjectData1.setCourseTargetId(question.getCouTarId());
			subjectData1.setQueAccess(question.getQueAccess());
			subjectData.add(subjectData1);
		}
		info.setSubject(subjectData);
		info.setTotal(questionDao.countQuestionByCon(courseId,typeId,keyword,diff));
		return info;
	}

	/**
	 * 检查重复的题目
	 * @param courseId   课程id
	 * @param subjectIds 题目列表
	 * @return 返回重复的题目列表
	 */
	@Override
	public List<RepeatQues> checkPaperRepeat(String courseId, List<String> subjectIds) {
		return questionPaperDao.checkRepeatQuestion(courseId,String.join(",",subjectIds));
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
	public Boolean setDisableQue(List<String> questionIds) throws Exception{
		for (String questionId : questionIds) {
			questionDao.setAccess(questionId);
		}
		return true;
	}
}
